//
//  XHVirtualAccountPaymentViewController.m
//  umibus
//
//  Created by fengyn on 16/6/28.
//  Copyright © 2016年 lexingsoft. All rights reserved.
//

#import "XHVirtualAccountPaymentViewController.h"
#import "XHPaySuccessViewController.h"
#import "XHPayFailureViewController.h"
#import "XHEditorPassWordViewController.h"

#import "Services.h"

#import <UIAlertView-Blocks/UIAlertView+Blocks.h>

@interface XHVirtualAccountPaymentViewController ()
@property (weak, nonatomic) IBOutlet UILabel *ui_payValueLabel;
@property (weak, nonatomic) IBOutlet UILabel *ui_accountLabel;
@property (weak, nonatomic) IBOutlet UILabel *ui_balanceLabel;
@property (weak, nonatomic) IBOutlet UIButton *ui_submitButton;
@property (strong, nonatomic) NSDictionary * m_userDic;

@end

@implementation XHVirtualAccountPaymentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title=@"余额支付";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getUserInfo];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)getUserInfo
{
    WS(weakSelf)
    self.m_userDic=[ServiceManager getUserInfoSuccess:^(NSDictionary *data) {
        weakSelf.m_userDic = data;
        [weakSelf updateView];
    } failure:^{
        
    }];
    [self updateView];
}

- (void)updateView{
    double balance=[self.m_userDic[@"cashoutBalance"] doubleValue];
    double yue=balance-self.amount;
    if (yue<0) {
        yue=0;
    }
    self.ui_balanceLabel.text=[NSString stringWithFormat:@"￥%.2f",yue];
    self.ui_payValueLabel.text=[NSString stringWithFormat:@"%.2f元",self.amount];
    self.ui_accountLabel.text=[NSString stringWithFormat:@"￥%.2f",balance];
}

- (void)goPaySuccessView{
    //去支付成功界面;
    XHPaySuccessViewController *viewController=[[XHPaySuccessViewController alloc] init];
    viewController.amount=self.amount;
    NSString *productType=self.productDic[@"productType"];
    if (self.orderDic) {
        productType=self.orderDic[@"orderType"];
    }
    viewController.productType=productType;
    if ([productType isEqualToString:kProductTypeFlowPackage])
    {
        viewController.type = @"package";
    }
    else
    {
        viewController.type = @"order";
    }
    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)goPayFailureView{
    //去支付失败界面;
    XHPayFailureViewController *viewController=[[XHPayFailureViewController alloc] init];
    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)submitActionWithPassword:(NSString *)password{
    WS(weakSelf)
    [self.navigationController.view setUserInteractionEnabled:NO];
    [PromptAction showWaitPrompt:@"正在支付..."];
    if (self.orderDic) {
        BOOL isIntelligent=NO;
        if ([self.orderDic[@"orderType"] isEqualToString:kProductTypeIntelligent]) {
            isIntelligent=YES;
        }
        [ServiceManager repayOrderWithOrderSn:self.orderDic[@"orderSn"] payMethod:kPayChannelYE password:password isIntelligent:isIntelligent success:^(NSDictionary *data) {
            [weakSelf goPaySuccessView];
            [self.navigationController.view setUserInteractionEnabled:YES];
            [PromptAction dismissPrompt];
        } failure:^(NSDictionary *data) {
            [self.navigationController.view setUserInteractionEnabled:YES];
            [PromptAction dismissPrompt];
            if ([data isKindOfClass:[NSDictionary class]]&&[data[@"message"] isEqualToString:@"wrong_paymentPassword"]) {
                RIButtonItem *cancelItem=[RIButtonItem itemWithLabel:@"忘记密码" action:^{
                    XHEditorPassWordViewController *viewController=[[XHEditorPassWordViewController alloc] init];
                    [self.navigationController pushViewController:viewController animated:YES];
                }];
                RIButtonItem *okItem=[RIButtonItem itemWithLabel:@"重试" action:^{
                    [self submitButtonAction:nil];
                }];
                UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"密码错误" message:@"输入密码不匹配" cancelButtonItem:cancelItem otherButtonItems:okItem, nil];
                [alertView show];
            }else{
                [weakSelf goPayFailureView];
            }
        }];
        return;
    }
    if (!self.score) {
        self.score=@"";
    }
    if (!self.couponNo) {
        self.couponNo=@"";
    }
    NSString *phoneNumber=@"";
    if (self.phoneNumber) {
        phoneNumber=self.phoneNumber;
    }
    NSString *phoneLocation=@"";
    if (self.operatorDic) {
        phoneLocation=self.operatorDic[@"provinceID"];
    }

    NSDictionary *product=@{self.productDic[@"sequenceNBR"]:@1};
    if (self.productDic2) {
        product=@{self.productDic[@"sequenceNBR"]:@1,
                  self.productDic2[@"sequenceNBR"]:self.productDic[@"packageCount"]};
    }
    NSString *amount=[NSString stringWithFormat:@"%.2f",self.amount];
    
    [ServiceManager createOrderWithProductType:self.productDic[@"productType"]
                                        amount:amount
                                     payMethod:kPayChannelYE
                                      products:product
                                      password:password
                                 phoneLocation:phoneLocation
                                   phoneNumber:phoneNumber
                                   submitToken:self.m_submitToken
                                         score:self.score
                                      couponNo:self.couponNo
                                       success:^(NSDictionary *data) {
                                           [weakSelf goPaySuccessView];
                                           [self.navigationController.view setUserInteractionEnabled:YES];
                                           [PromptAction dismissPrompt];
    } failure:^(NSDictionary *data) {
        [self.navigationController.view setUserInteractionEnabled:YES];
        [PromptAction dismissPrompt];
        if ([data isKindOfClass:[NSDictionary class]]&&[data[@"message"] isEqualToString:@"wrong_paymentPassword"]) {
            RIButtonItem *cancelItem=[RIButtonItem itemWithLabel:@"忘记密码" action:^{
                XHEditorPassWordViewController *viewController=[[XHEditorPassWordViewController alloc] init];
                [self.navigationController pushViewController:viewController animated:YES];
            }];
            RIButtonItem *okItem=[RIButtonItem itemWithLabel:@"重试" action:^{
                [self submitButtonAction:nil];
            }];
            UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"密码错误" message:@"输入密码不匹配" cancelButtonItem:cancelItem otherButtonItems:okItem, nil];
            [alertView show];
        }else{
            [weakSelf goPayFailureView];
        }
    }];
}



- (IBAction)submitButtonAction:(UIButton *)sender {
    RIButtonItem *cancelItem=[RIButtonItem itemWithLabel:@"取消"];
    UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"请输入密码" message:@"登录密码即支付密码" cancelButtonItem:cancelItem otherButtonItems: nil];
    alertView.alertViewStyle=UIAlertViewStyleSecureTextInput;
    RIButtonItem *okItem=[RIButtonItem itemWithLabel:@"确定" action:^{
        UITextField *textField=[alertView textFieldAtIndex:0];
        NSString *password=textField.text;
        if ([NSString checkNullString:password]) {
            [PromptAction showErrorPrompt:@"密码不能为空"];
        }else{
            [self submitActionWithPassword:password];
        }
    }];
    [alertView addButtonItem:okItem];
    [alertView show];
}

@end
